<?php
/**
 * Save.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/06/07
 * Time: 14:04
 */
namespace app\api\open\role;

use app\api\model\SimpleRbacRole;
use app\api\open\Base;
use think\Db;
use think\Validate;

class Save extends Base
{
    protected $role_id = null;
    protected $roleData = [];
    /**
     * Save constructor.
     * @throws \Exception
     */
    public function __construct($param=[])
    {
        $this->prevent();

        parent::__construct($param);

        $param = $this->params;

        // 验证请求参数
        $validate = new Validate([
            // step1
            "name" => "require",
            "remark" => "require",
            "nodes" => "require"
        ]);
        $check = $validate->check($param);
        if($check === false){
            // 验证失败 输出错误信息
            throw new \Exception($validate->getError(),1);
        }
        if(!empty($param['id']))
        {
            $this->role_id = $param['id'];
        }
        // 角色名称
        $this->roleData['name'] = $param['name'];
        // 角色简介
        $this->roleData['remark'] = $param['remark'];
        // 节点(,1,2,3,)
        $deCodeNodes = json_decode($param['nodes'],true);
        if(empty($deCodeNodes))
        {
            $this->roleData['nodes'] = '';
        }else{
            $this->roleData['nodes'] = ','.implode(",",$deCodeNodes).',';
        }
        // 是否启用(0:否,1:是)
        $this->roleData['status'] = empty($param['status'])?0:1;
        // 平台ID
        $this->roleData['platform_id'] = config('platform_info.id');

    }

    public function index($param=[])
    {
        Db::startTrans();
        try
        {
            // 保存商品主表信息
            $role_id = SimpleRbacRole::getInstance()->save($this->role_id,$this->roleData);
            if(!$role_id)
            {
                throw new \Exception("保存角色信息失败",2);
            }
        }
        catch (\Exception $e)
        {
            // 出现错误进行回滚处理
            Db::rollback();
            // 统一错误抛出
            throw new \Exception("保存失败：".$e->getMessage(),$e->getCode());
        }

        Db::commit();
        return ['id'=>empty($this->role_id)?$role_id:$this->role_id];
    }
}